import { Card, FormProps, Space, Table, TableProps, Tag } from "antd"

import {
  ExclamationCircleOutlined,
  PlusOutlined
} from '@ant-design/icons';
import { Status } from "@/utils/enum";
import { message, modal } from "@/utils/AntdGlobal";
import { categoryItem, categoryParams } from "@/types/category";
import { deleteCategoryApi, getCategoryListApi, updateStatusApi } from "@/api/category";
import { AddCategory } from './addCategory'
import { AddCategoryRef } from "@/types/childCompRef";
export const Component = () => {
  const { Option } = Select;
  const columns: TableProps<categoryItem>['columns'] = [
    {
      title: '分类名称',
      dataIndex: 'name',
      key: 'name',
      align: "center"
    },
    {
      title: '分类类型',
      dataIndex: 'type',
      key: 'type',
      align: "center",
      render: (data: number) => {
        return <div>{data === 1 ? '菜品分类' : '套餐分类'}</div>
      }
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      align: "center"
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: "center",
      render: (data: number) => {
        return <Tag color={Status[data].type}>{Status[data].name}</Tag>
      }
    },
    {
      title: '操作时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      align: "center"
    },
    {
      title: '操作',
      align: "center",
      render: (data: categoryItem) => {
        return (
          <Space size="middle">
            <a style={{ color: "#0e8b8d" }} onClick={() => editCate(data)}>修改</a>
            <a style={{ color: "red" }} onClick={() => deleteCategory(data)}>删除</a>
            <a style={{ color: data.status ? "red" : "#0e8b8d" }} onClick={() => updateStatus(data)}>{data.status ? '禁用' : '启用'}</a>
          </Space >
        )
      },
    },
  ];
  // 定义数据
  const [categoryList, setCategoryList] = useState<categoryItem[]>([])
  // 定义总数
  const [total, setTotal] = useState(0)
  // 定义参数
  const [categoryQuery, setCategoryQuery] = useState<categoryParams>({
    name: '',
    type: undefined,
    page: 1,
    pageSize: 10
  })
  // 定义id
  const [categoryId, setCategoryId] = useState<number>()
  // 修改页码
  const changePage = (page: number, pageSize: number) => {
    setCategoryQuery({
      ...categoryQuery,
      page,
      pageSize,
    })
  }
  // 获取数据
  useEffect(() => {
    const getCategoryList = async () => {
      // 发请求获取数据
      const res = await getCategoryListApi(categoryQuery)
      const { data } = res
      setTotal(data.total)
      setCategoryList(data.records)
    }
    getCategoryList()
  }, [categoryQuery])
  type FieldType = {
    name?: string;
    type?: string | undefined
  };

  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    setCategoryQuery({
      ...categoryQuery,
      name: values.name,
      type: values.type ? +values.type : undefined
    })
  };
  // 修改状态
  const updateStatus = (data: categoryItem) => {
    modal.confirm({
      title: data.status ? '禁用分类' : '启用分类',
      icon: <ExclamationCircleOutlined />,
      content: '确认调整该分类的状态?',
      centered: true,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        let status = data.status ? 0 : 1
        const res = await updateStatusApi(data.id, status)
        if (res.code === 1) {
          message.success(`该分类${data.status ? '禁用成功' : '启用成功'}`)
          setCategoryQuery({
            ...categoryQuery,
            page: 1,
            pageSize: 10,
            name: categoryQuery.name
          })
        }
      }
    });
  }
  // 删除员工
  const deleteCategory = (data: categoryItem) => {
    modal.confirm({
      title: '删除分类',
      icon: <ExclamationCircleOutlined />,
      content: '确认要删除该分类嘛?',
      centered: true,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const res = await deleteCategoryApi(data.id)
        if (res.code === 1) {
          message.success('删除成功')
          setCategoryQuery({
            ...categoryQuery,
            page: 1,
            pageSize: 10,
            name: categoryQuery.name
          })
        }
      }
    });
  }
  // 获取组件的ref
  const addCategory = useRef<AddCategoryRef>(null)
  // 添加分类
  const addCate = () => {
    addCategory.current!.showModal()
  }
  // 修改分类
  const editCate = (data: categoryItem) => {
    setCategoryId(data.id)
    addCategory.current!.getCategoryDetail(data.id)
    addCategory.current!.showModal()
  }
  // 添加成功
  const onSuccess = useCallback(() => {
    setCategoryQuery({
      ...categoryQuery,
      page: 1,
      pageSize: 10,
      name: categoryQuery.name
    })
  }, [])
  return (
    <div style={{ width: '100%', height: '100%', overflow: 'hidden' }}>
      {/* 查询 */}
      <Card className="mb-4">
        <div className="flex flex-justify-between">
          <Form
            name="basic"
            layout="inline"
            labelCol={{ span: 8 }}
            onFinish={onFinish}
            autoComplete="off"
          >
            <Form.Item<FieldType>
              label="分类名称"
              name="name"
            >
              <Input placeholder="请输入分类名称" allowClear />
            </Form.Item>
            <Form.Item<FieldType> style={{ width: 250 }} name="type" label="分类类型">
              <Select
                placeholder="请选择分类类型"
                allowClear
              >
                <Option value="1">菜品分类</Option>
                <Option value="2">套餐分类</Option>
              </Select>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </Form.Item>
          </Form>
          <Button type="primary" icon={<PlusOutlined />} onClick={addCate}>
            添加分类
          </Button>
          <AddCategory ref={addCategory} title={categoryId ? '修改分类' : '添加分类'} onSuccess={onSuccess} categoryId={categoryId} />
        </div>
      </Card>
      {/* 表格 */}
      <Card style={{ overflow: 'auto', height: 'calc(100% - 98px)' }}>
        <Table<categoryItem> rowKey="id" bordered dataSource={categoryList} columns={columns} pagination={
          {
            total: total,
            showQuickJumper: true,
            showSizeChanger:true,
            showTotal: (total) => `总数 ${total} 条`,
            position: ["bottomCenter"],
            onChange: (page, pageSize) => changePage(page, pageSize)
          }
        } />
      </Card>
    </div>
  )
}
